/**
 * 全新通用auth授权逻辑
 */
const config = require('./config');
let app = getApp();
let pageCallbackFnArray = []; // 登录后统一回调方法

let auth_common = {
  // 重新获取 login_token
  doLogin(pageCallbackFn) {
      if (pageCallbackFn && typeof pageCallbackFn == "function") {
          pageCallbackFnArray.push(pageCallbackFn);
          if (pageCallbackFnArray.length > 1) {
              return;
          }
      }
      // 登录
      wx.login({
          success: res => {
              var wxCode = res.code;
              let subData = {
                appId: config.appid,
                wxCode: wxCode,
                appletType: 3
              };
              wx.request({
                  url: config.pageDomain + "/v2/api/applet/commonly/authorize/loginToken",
                  method: "POST",
                  data: subData,
                  header: {
                      "content-type": "application/json"
                  },
                  success: getTokenRes => {
                      if (getTokenRes.data.code == 0) {
                          console.log("getAppletGameToken success");
                          var loginToken = getTokenRes.data.model.loginToken;
                          // 同步登录信息到异步缓存
                          wx.setStorageSync("login_token", loginToken);
                          // 同步信息到全局变量
                          app.globalData.loginToken = loginToken;
                          // 回调原来的方法
                          while (pageCallbackFnArray.length > 0) {
                              let callbackFn = pageCallbackFnArray.pop();
                              callbackFn.call();
                          }
                          // pageCallbackFn && pageCallbackFn.call();
                      } else {
                          var errMsg = getTokenRes.data.msg;
                          if (getTokenRes.data.ret == -40000) {
                              errMsg = "请检查配置参数";
                          }
                          // wx.showModal({ content: "getAppletGameToken #222" + errMsg });
                          console.log({ content: "getAppletGameToken #222" + errMsg });
                      }
                  },
                  fail: function () {
                      wx.showModal({ content: "请检查您的网络状态" });
                  }
              });
          }
      });
  },
  // 执行登录操作
  initContext(pageCallbackFn) {
     // checkLogin
     // 检查本地的 login_token，last_gettoken_time
     // 检查 user_info
      wx.checkSession({
          success: () => {
              // session 未过期，并且在本生命周期一直有效

              // 获取本地的login_token
              var login_token = wx.getStorageSync("login_token");

              if (login_token) {
                  // 如果有本地的登录凭证
                  pageCallbackFn && pageCallbackFn.call();
              } else {
                  this.doLogin(pageCallbackFn);
              }
          },
          fail: () => {
              // 登录状态已经过期
              console.log("wx.checkSession fail");
              this.doLogin(pageCallbackFn);
          }
      });

  },

  //校验是否登录
  checkUserInfo() {
    // const userInfo = app.globalData.userInfo;
    //  this.setData({
    //   userInfo,
    //   needGetUserInfo: !userInfo ? true : false
    // })
    const userInfo = checkUserInfo
    return userInfo ? true : false
  },

  getUserInfo(res,callback) {
    let userInfo = res.detail.userInfo

    if (userInfo) {
        var loginToken = wx.getStorageSync("login_token");
        wx.request({
            url: config.pageDomain + '/api/applet/user/manager/save/user/info',
            method: "POST",
            data: {
                encryptedData: res.detail.encryptedData,
                iv: res.detail.iv
              },
            header: Object.assign({
                'content-type': 'application/json', // application/json & application/x-www-form-urlencoded
                loginToken
            }),
            success:(res) => {
                let data = res.data
                if (data.code === 0) {
                  app.globalData.userInfo = userInfo;
                  // 保存用户信息
                  wx.setStorageSync("user_info", userInfo);
                  if( callback && typeof callback == "function" ){
                    callback(userInfo);
                  }
                  console.log('保存用户信息成功！')
                } else {
                  wx.showModal({
                    title: '提示',
                    content: '网络出现异常，请推出小程序重试~',
                    showCancel: false
                  })
                }
          },
          fail: () => {
            console.log('请求保存用户信息失败！')
            return;
          }
        });
    } else {
      wx.showModal({
        title: '用户授权',
        content: "拒绝授权将无法体验完整功能，建议打开授权",
        showCancel: false
      })
    }
  }
}

module.exports = auth_common;
